package com.njsf.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.njsf.annotation.Token;
import com.njsf.dto.ResponseJson;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

public class TokeInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            String jsonStr = objectMapper.writeValueAsString(new ResponseJson(101, "不能重复提交!"));
            response.setCharacterEncoding("UTF-8");
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            boolean hasToken = method.isAnnotationPresent(Token.class);
            if (!hasToken)
                return true;
            Token token = method.getAnnotation(Token.class);
            if (token.create()){
                String tokenStr = UUID.randomUUID().toString();
                request.setAttribute("token", tokenStr);
                request.getSession().setAttribute("token",tokenStr);
                return true;
            }
            if(token.remove()){
                String clientToken = request.getHeader("token");
                if (clientToken == null){
                    response.getWriter().write(jsonStr);
                    return false;
                }
                String serverToken = (String) request.getSession().getAttribute("token");
                if (serverToken == null){
                    response.getWriter().write(jsonStr);
                    return false;
                }
                if (!clientToken.equals(serverToken)){
                    response.getWriter().write(jsonStr);
                    return false;
                }
                request.getSession().removeAttribute("token");
            }
            return true;
        }else{
            return true;
        }
    }
}
